package com.example.config;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

@Slf4j
@Component
public class MyWebSocketHandler implements WebSocketHandler {

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        //连接成功之后，应该在这个方法中将session保存起来，通常都用
        //一个Map来保存，key是用户ID（或其他唯一标识），这样的话想
        //给哪个用户发送消息，那么就直接拿到那个用户的session，然后
        //调用session.sendMessage方法发送消息就可以了
        log.info("连接成功");
    }


    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        log.info("客户端过来一条消息，内容是:" + message.getPayload().toString());
//        TextMessage textMessage = new TextMessage(JSONObject.toJSONString("客户端你好，我已经收到你的消息"));
//        session.sendMessage(textMessage);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.info("错误处理");
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {
        log.info("连接关闭");
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
